﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMS.Common;
using WMS.Common.JWT;
using WMS.Model;
using WMS.Repository.IRepository;
using WMS.Service.IService;
using WMS.Service.Redis;

namespace WMS.Service
{
    public class LogService : BaseServices<UserModel>, ILogService
    {
        private readonly ILogRepository _logRepository;
        private readonly IRedisService _redisService;
        private readonly IAvatarService _avatarService;

        public LogService(IBaseRepository<UserModel> repository,
            ILogger<BaseServices<UserModel>> logger,
            IAvatarService avatarService,
            ILogRepository logRepository, IRedisService redisService) : base(repository, logger)
        {
            _logRepository = logRepository;
            _redisService = redisService;
            _avatarService = avatarService;
        }

        /// <summary>
        /// 账号登录
        /// </summary>
        public async Task<(bool Success, string Message, object obj)> AccountLoginAsync(string account, string password)
        {
            try
            {
                UserModel user = await _logRepository.GetAccountAsync(account);

                if (user == null)
                {
                    return (false, "账号不存在", null);
                }

                if (user.Password == MD5Helper.EncryptPassword(password))
                {
                    var token = JwtHelper.GenerateUserToken(user);
                    string avatarUrl = await _avatarService.GetAvatarUrlByUserCodeAsync(user.UserCode);

                    // 创建匿名对象返回给前端
                    var result = new
                    {
                        token = token,
                        user = new
                        {
                            id = user.Id,
                            account = user.Account,
                            realName = user.Realname,
                            phone = user.Phone,
                            email = user.Email,
                            userCode = user.UserCode,
                            department = user.Department,
                            createTime = user.CreateTime,
                            avatarUrl = avatarUrl  // 添加头像URL
                        }
                    };

                    return (true, "登录成功", result);
                }
                else
                {
                    return (false, "密码错误", null);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"账号登录失败 - 账号: {account}");
                throw;
            }
        }

        /// <summary>
        /// 发送邮箱验证码
        /// </summary>
        public async Task<(bool Success, string Message)> EmailCodeAsync(string email)
        {
            try
            {
                UserModel user = await _logRepository.GetEmailAsync(email);

                if (user == null)
                {
                    return (false, "邮箱不存在！");
                }

                string code = CodeHlper.Code();
                if (await EmailTemplateHelper.SendAsync(email, "登录验证码", code))
                {
                    await _redisService.SetAsync(email, code, TimeSpan.FromMinutes(2));
                    return (true, "发送成功！");
                }
                else
                {
                    return (false, "发送失败，请重新发送！");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"发送邮箱验证码失败 - 邮箱: {email}");
                throw;
            }
        }

        /// <summary>
        /// 邮箱登录
        /// </summary>
        public async Task<(bool Success, string Message, object obj)> EmailLoginAsync(string email, string code)
        {
            try
            {
                UserModel user = await _logRepository.GetEmailAsync(email);
                if (user == null)
                {
                    return (false, "邮箱不存在！", null);
                }

                string emailCode = await _redisService.GetAsync<string>(email);
                if (emailCode == null)
                {
                    return (false, "验证码已过期，请重新发送！", null);
                }

                if (emailCode != code)
                {
                    return (false, "验证码错误！", null);
                }

                var token = JwtHelper.GenerateUserToken(user);
                string avatarUrl = await _avatarService.GetAvatarUrlByUserCodeAsync(user.UserCode);

                // 创建匿名对象返回给前端
                var result = new
                {
                    token = token,
                    user = new
                    {
                        id = user.Id,
                        account = user.Account,
                        realName = user.Realname,
                        phone = user.Phone,
                        email = user.Email,
                        userCode = user.UserCode,
                        department = user.Department,
                        createTime = user.CreateTime,
                        avatarUrl = avatarUrl  // 添加头像URL
                    }
                };

                return (true, "登录成功", result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"邮箱登录失败 - 邮箱: {email}");
                throw;
            }
        }
    }
}